<template>
    <div class="main">
        <el-card class="box-card" :body-style="{height: '100%'}">
            <!-- 搜索栏 -->
            <el-row class="search" style="display: flex;">
                <span class="title">创建时间：</span>
                <el-date-picker v-model="date" type="date" placeholder="开始日期"></el-date-picker>
                <div style="margin-left: -20px;"><el-date-picker v-model="endDate" type="date" placeholder="结束日期"></el-date-picker></div>
                <span class="title">员工：</span>
                <el-input v-model="form.query.userName" clearable placeholder="请输入内容"></el-input>
                <el-button @click="getAccout">搜索</el-button>
                <el-button type="primary" @click="showDialog(null)">添加</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table v-loading="loading"  :data="tableData" border style="width: 100%">
                <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
                <el-table-column prop="userName" label="绑定员工" align="center" width="100"></el-table-column>
                <el-table-column prop="phone" label="手机号" align="center" width="150"></el-table-column>
                <el-table-column prop="roleID" label="账号类型" align="center" width="150" :formatter="formatterType"></el-table-column>
                <el-table-column prop="createtime" label="创建时间" align="center" width="180"></el-table-column>
                <el-table-column prop="name" label="操作"  align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" @click="showDialog(1, scope.row)">编辑</el-button>
                        <el-button type="danger" @click="deleteUser(scope.row.userid)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 弹窗 -->
        <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="500px">
            <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="绑定员工：" prop="userName">
                    <el-input el-input v-model.number="ruleForm.userName" placeholder="请输入员工姓名"></el-input>
                </el-form-item>
                <el-form-item label="账号类型：" prop="roleId">
                    <el-select v-model="ruleForm.roleId" placeholder="请选择账号类型" style="width: 100%;" @change="change()">
                        <el-option label="管理员" :value="1"></el-option>
                        <el-option label="配送员" :value="2"></el-option>
                        <el-option label="服务员" :value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号：">
                    <el-input el-input v-model.number="ruleForm.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item v-if="title == '新增账号'" label="密码：">
                    <el-input type="password" v-model="ruleForm.password" autocomplete="off" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item v-if="title == '新增账号'" label="确认密码">
                    <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off" placeholder="请确认密码"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data () {
        return {
            date: '',
            endDate: '',
            form: {// 请求参数
                query:{
                    userName: "",
                    roleID: "",
                    companyID: "",
                    userid: "",
                    phone: "",
                    userTime: "",
                    userEndTime: ""
                },
                pageInfo:{
                    pageNum: 1,
                    pageSize: 2000
                }
            },
            dialogVisible: false,// 是否显示弹窗
            tableData: [],// 表格数据
            ruleForm: {// 弹窗参数
                userName: '',
                password: '',
                phone: '',
                roleId: '',
                checkPass: '',
            },
            rules: {// 验证规则
                userName: [
                    { required: true, message: '请输入绑定员工', trigger: 'blur' }
                ],
                roleId: [
                    { required: true, message: '请选择账号类型', trigger: 'blur' }
                ],
            },
            loading: false,
            title: ''// 弹窗标题
        }
    },
    mounted () {
        // 页面加载获取账号信息
        this.getAccout()
    },
    methods: {
        change () { // select变化时更新视图
            this.$forceUpdate()
        },
        formatterType (row) {// 根据roleID显示不用的角色名称
            if (row.roleID == 1) return '管理员'; 
            else if (row.roleID == 2) return '配送员';
            else if (row.roleID == 3) return '服务员';
        },
        getAccout () {// 获取账号数据
            // 过滤创建时间
            if (this.date && this.endDate) {
                this.form.query.userTime =  this.date.getFullYear() + '-' + (this.date.getMonth()+1) + '-' + this.date.getDate() + ' 00:00:00'
                this.form.query.userEndTime = this.endDate.getFullYear() + '-' + (this.endDate.getMonth()+1) + '-' + this.endDate.getDate() + ' 23:59:00'
                if (this.form.query.userTime == this.form.query.userEndTime) {
                    this.$message({type: 'error', message: '搜索时间至少间隔一天'})
                    return
                }
            } else {
                this.form.query.userTime = this.form.query.userEndTime = ''
            }
            this.loading = true// 显示加载
            this.$http.post('user/queryAllUserUnit',this.form).then(res => {// 请求用户列表
                this.loading = false// 关闭加载
                if (res.data.meta.status == 200) {// 请求成功
                    let data = []
                    for (let i=0; i<res.data.data.list.length; i++) {// 过滤掉顾客的账号，不应在管理系统角色显示
                        if (res.data.data.list[i].roleID != 999) {
                            data.push(res.data.data.list[i])
                        }
                    }
                    this.tableData = data
                } else {
                    this.$message({type: 'error', message: '获取失败'})
                }
            })
        },
        confirm () {// 提交表单
            this.$refs['ruleForm'].validate((valid) => {// 预验证
                if (valid) {
                    if (this.title == '新增账号') {
                        // 新增账号校验密码
                        if (this.ruleForm.password == '') {
                            this.$message({type: 'error', message: '请输入密码'})
                            return
                        }
                        if (this.ruleForm.password != this.ruleForm.checkPass) {
                            this.$message({type: 'error', message: '确认密码不一致，请重新确认'})
                            return
                        }
                        // 注册
                        this.register()
                    } else {
                        // 修改用户信息
                        this.updateUser()
                    }
                    
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        updateUser () { // 修改用户信息
            this.$http.post('user/personInfo/update', this.ruleForm).then(res => {
                if (res.data.meta.status == 200) {
                    this.$message({type: 'success', message: '修改成功！'})
                    this.dialogVisible = false
                    this.getAccout()
                } else {
                    this.$message({type: 'error', message: '修改失败！'})
                }
            })
        },
        register () {//注册
            this.$http.post('user/register', {//根据用户名和密码注册账号
                userName: this.ruleForm.userName,
                password: this.ruleForm.password
            }).then(res => {
                if (res.data.meta.status == 200) { //注册成功，激活账户并根据选中的角色类型进行设置
                    this.$http.post('user/personInfo/update', {
                        userId: "",
                        userName: this.ruleForm.userName,
                        companyID: 1,
                        remark:"",
                        roleId: this.ruleForm.roleId,
                        status: 1,
                        phone: this.ruleForm.phone
                    }).then(res => {
                        if (res.data.meta.status == 200) {
                            this.$message({type: 'success', message: '添加成功！'})
                            this.dialogVisible = false
                            this.getAccout()
                        } else {
                            this.$message({type: 'error', message: '添加失败！'})
                        }
                    })
                } else {
                    this.$message({type: 'error', message: '添加失败！'})
                }
            })
        },
        // 根据不同的点击位置，显示编辑或者新增
        showDialog (type, data) {
            if (type == 1) {// 编辑预先赋值所点击行的数据
                this.title = '编辑账号'
                data.roleId = data.roleID
                this.ruleForm = data
                this.dialogVisible = true
                return
            }
            // 新增清空表单值
            this.title = '新增账号'
            this.ruleForm = {
                userName: '',
                password: '',
                phone: '',
                roleId: '',
                checkPass: '',
            }
            this.dialogVisible = true
        },
        // 根据id删除账户
        deleteUser (userid) {
            this.$http.put('user/delete/' + userid).then(res => {
                if (res.data.meta.status == 200) {
                    this.$message({type: 'success', message: '删除成功！'})
                    this.getAccout()
                } else {
                    this.$message({type: 'error', message: '删除失败！'})
                }
            })
        }
    }
}
</script>

<style scoped>
.main {
    height: 100%;
}
.el-card {
    height: 100%;
}
.el-table {
    height: calc(100% - 150px);
    overflow: auto;
}
.search {
    display: flex;
    margin-bottom: 20px;
}
.search .title {
    display: block;
    margin-right: 10px;
    text-align: right;
    line-height: 35px;
}
.search .el-input, .search .el-select, .search .el-date-picker {
    margin-right: 40px;
    width: 200px;
}
</style>